import { C42ShopItemList, Header, Layout, WithMargins } from "@/components";
import { useEffect, useState } from "react";
import { useRouter } from "@tarojs/taro";
import {
  getShopItemsOfType,
  useApplicationInfo,
} from "@/store/applicationDataContext";
import { ApiShopItemsMapping } from "@/data/shop/shopTypes";
import { ShopItemListingShape } from "@/data/shop/shopItemListingTypes";
import { View } from "@tarojs/components";
import style from "./index.module.scss";
import { sendAction, ActionNames } from "@/utils/tracking";

function ShopItemList() {
  const { dispatch } = useApplicationInfo();
  const { params } = useRouter();
  // Note: should never be publication
  const [type, setType] = useState<null | ApiShopItemsMapping>(null);
  const [list, setList] = useState<null | ShopItemListingShape[]>(null);

  useEffect(() => {
    if (params.id) {
      const type = +params.id! as ApiShopItemsMapping;
      setType(type);

      if (type === ApiShopItemsMapping.Giftcertificate) {
        sendAction(ActionNames.GiftCardListImpression);
      } else {
        sendAction(ActionNames.SouvenirListImpression);
      }

      const getShopList = async () => {
        const data = await getShopItemsOfType(type, dispatch);
        if (data) {
          setList(data);
        }
      };
      getShopList();
    }
  }, [dispatch]);

  return (
    <Layout>
      <View className={style["shop-item-list-wrapper"]}>
        <WithMargins>
          <Header type={"heading-l"}>
            {type === ApiShopItemsMapping.Giftcertificate ? "礼品卡" : "纪念品"}
          </Header>
        </WithMargins>
        {list && (
          <C42ShopItemList shopItemList={list} cardType="product-card-short" />
        )}
      </View>
    </Layout>
  );
}

export default ShopItemList;
